define(['config', 'text!app/module/system/produce.html', 'laypage',
    'mydialog', 'autocomplete','jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
    mydialog, autocomplete,jqGrid,common, laydate) {
	
	var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_url = "/api/produce";
    
    var item = 0;
    
    var temp = 0;
    
    var amount = 0;
    
    var decCm ;
 
    var orderNo;
    
    var goodsUuid = new Array();
    
    function b(val, opt, row) {
        
      	 var html_con = '<div class="register1" data-id="' + row.id + '"><a class = "register" id="register"><span>登记</span></a></div>';
      	 return html_con;
       };
    
    var model = avalon.define({
    	$id : "produce",
         // 查询条件,
    	
    	orderNo:"000",
    	productiondetailInfo:{
    		id:"",
        	uuid:"",
        	sku:"",
        	name:"",
        	orderNo:"",
        	model:"",
        	amount:"",
        	already:"",
        	alreadyOut:"",
        	goodsUuid:"",
        	lotNo:"",
        	registerAmount:"",
    		register:"",
    		registerDate:""
    	},
    	
    	
    	productionInfo:{
    		id:"",
     		uuid:"",
     		productionNo:"",
     		startingDate:"",
     		destination:"",
     		goodsUuid:"",
     		freightForwarding:"",		
     		ceva:"",
     		samDepartment:"",
     		totalQuantity:"",
     		qcDepartment:"",
     		productDepartment:"",
     		examination:"",
     		comment:"",
     		orderNo:"",
     		status:"",
     		issuedDate:""
    	},
        query: {
        	productionNo:"",
        },

         statusArr: [],
         selected: [],
         roles: [],
         init: function () {
             model.loadGrid();
             model.addEvent();
             model.loadGrid_d();
             model.loadGrid_m();
         },
         loadGrid: function () {
             function t(val, opt, row) {
                 
            	 var html_con = '<div class="see" data-id="' + row.id + '"><a class = "view" id="detail"><span>查看</span></a></div>';
            	 return html_con;
             }
           var i = Public.setGrid();
             
             $("#grid").jqGrid({
                 loadBeforeSend: function (jqXHR) {
                     jqXHR.setRequestHeader("X-AuthToken", token);
                 },
                 datatype: "json",
                 mtype: "POST",
                 url: grid_url+"/getList",
                 loadComplete: function (data) {
                	 console.log('[data234234234]',data);
                	 
                 },
                 loadError: function (xhr, status, error) {
                     alert(JSON.parse(xhr.responseText).msg);
                 },
                 colModel: [{
                         name: "operating",
                         label: "操作",
                         width: '5%',
                         formatter: t,
                     },
                     {
                         name: "productionNo",
                         label: "生产指令号",
                         width: '12%',
                     },
                     {
                         name: "destination",
                         label: "目的港",
                         width: '10%',
                     },
                     {
                         name: "startingDate",
                         formatter: Public.dateFormat,
                         label: "投产日期",
                         width: '13%',
                     },
                     {
                         name: "totalQuantity",
                         label: "总数量",
                         width: '10%',
                     },
                     {
                         name: "examination",
                         label: "审核",
                         formatter:function(value,options,rowData){
                        	 if(value===0){
                        		 return '未审核';
                        	 }else if(value===1){
                        		 
                        		 return '已审核';
                        	 }else{
                        		 return '';
                        	 }
                        	 
                         },
                         width: '10%',
                     },
                     {
                         name: "already",
                         label: "已生产总数",
                         width: "7%"
                     },
                     {
                         name: "alreadyOut",
                         label: "已出库总数",
                         width: '13%',
                        
                     },
                     {
                         name: "status",
                         label: "状态",//生产中，生产完成
                         width: '14%',
                         formatter:function(value,options,rowData){
                        	 if(value===0){
                        		 return '';
                        	 }else if(value===1){
                        		 
                        		 return '已完成';
                        	 }else{
                        		 return '';
                        	 }
                        	 
                         },
                     },
                     {
                         name: "issuedDate",
                 	     formatter: Public.custDatefmter,
	                         label: "下达指令日期",
                         width: '15%',
                     },
                     {
                    	 name:"orderNo",
                    	 label:"订单号",
                    	 hidden:true
                     }
                 ],
                 cmTemplate: {
                     sortable: false,
                     title: false,
                     align: "center"
                 },
                 //分页
                 page: 1,
                 rowNum: 10,
                 rowList: [10, 20, 30],
                 height: 300,
                 autowidth: true,
                 pager: '#page',
                 sortname: 'id',
                 viewrecords: true,
                 forceFit: false,
                 rownumbers: true,
                 multiselect: true,
                 multiboxonly: true,
                 sortorder: "desc",
                 /* 单击行数据   显示从表*/
                 onSelectRow: function(rowId) {
                	 
                	 orderNo = $("#grid").jqGrid("getRowData", rowId).orderNo;
                     console.log('[orderNo]',orderNo);
                     
                     model.reLoadGrid_d();
                     model.reLoadGrid_m();
                 },
                 jsonReader: {
                     root: "data.list",
                     records: "data.totalRow",
                     total: "data.totalPage",
                     repeatitems: false,
                     id: "id"
                 },
                 loadError: function () {
                     parent.Public.tips({
                         type: 1,
                         content: "加载数据异常！"
                     })
                 }
             });

         },
        loadGrid_d: function () {
        	console.log('[item]',item);
        		/**
        		 * 生产任务单明细
        		 */
        		$("#grid_d").jqGrid({
                    loadBeforeSend: function (jqXHR) {
                        jqXHR.setRequestHeader("X-AuthToken", token);
                    },
                    datatype: "json",
                    url: grid_url+"/getDetailList",
                    mtype: 'POST',
                    postData: {
                       "orderNo":model.orderNo
                    },
                    loadComplete: function (data) {
                    	console.log('[data*********************************]',data);
                    	
//                    	for (var i = 0; i < data.data.list.length; i++){
//                    		data.data.list[i].amount;
//                    		temp = data.data.list[i].amount + temp;
//						}
                    	
                    },
                    loadError: function (xhr, status, error) {
                    	alert(JSON.parse(xhr.responseText).msg);
                    },
                    colModel: [
                    {
                        name: "orderNo",
                        label: "订单号",
                        width: '8%',
                    },
                    {
                        name: "sku",
                        label: "sku",
                        width: '10%',
                    },
                    {
                        name: "name",
                        label: "品名",
                        width: '13%',
                    },
                    {
                        name: "lotNo",
                        label: "批次号",
                        width: '10%',
                    },
                    {
                        name: "model",
                        label: "规格型号",
                        width: '7%',
                    },
                    {
                        name: "amount",
                        label: "总数",
                        width: '7%',
                        formatter:function(value,options,rowData){
                        	amount = value;
                        	return value;
                       	 
                        },
                    },
                    {
                        name: "already",
                        label: "已生产总数",
                        width: "7%"
                    },
                    {
                        name: "alreadyOut",
                        label: "已出库总数",
                        width: '7%',
                       
                    },
                    {
                        name: "in",
	                     label: "成品入库",
                         width: '5%',
                         formatter: b,
                    },
                    {
                        name: "goodsUuid",
	                    label: "商品uuid",
                        width: '0%',
                        hidden:true,
                    },
                    {
                        name: "uuid",
	                    label: "商品uuid",
                        width: '0%',
                        hidden:true
                    },
                    {
                		name:'orderDetailUuid',
                		label:'订单明细uuid',
                		hidden:true
                	},
                    
                ],
                    cmTemplate: {
                        sortable: false,
                        title: false
                    },
                    page: 1,
                    rowNum: 10,
                    rowList: [10, 20, 30],
                    pager: '#page_d',
                    sortname: 'id',
                    viewrecords: true,
                    forceFit: false,
                    rownumbers: true,
                    multiselect: true,
                    multiboxonly: true,
                    sortorder: "desc",
                    autoScroll: false,
                    height: 150,
                    altRows: true,
                    gridview: true,
                    autowidth: true,
                    jsonReader: {
                        root: "data.list",
                        records: "data.totalRow",
                        total: "data.totalPage",
                    },

                });
        },
        
        loadGrid_m:function(){
    		/**
    		 * 所需原料清单
    		 */
    		$("#grid_m").jqGrid({
                loadBeforeSend: function (jqXHR) {
                    jqXHR.setRequestHeader("X-AuthToken", token);
                },
                contentType: "application/json;charset=utf-8",
                datatype: "json",
                url: grid_url+"/getLoss",
                mtype: 'POST',
                postData: {
                	"orderNo":model.orderNo
                },
                loadComplete: function (data) {
                	console.log('[data-*/-*/-*/-*/-*/-*/-*/-*/-*/]',data);
                	
//                	for (var i = 0; i < data.data.list.length; i++){
//                		data.data.list[i].amount;
//                		temp = data.data.list[i].amount + temp;
//					}
                	
                },
                loadError: function (xhr, status, error) {
//                             alert(JSON.parse(xhr.responseText).msg);
                },
                colModel : [
                            {
                            	name : 'pn',
                            	label:"料号",
                            	width : 180,
                            	hidden:true,
                        	},
                        	{
                        		name : 'name',
                        		label:"原料名称",
                        		width : 180,
                    		},
                    		{
                    			name : 'model',
                    			label:"规格型号",
                    			width : 80,
            				},
            				{
            					name:'goodsUuid',
            					label:'goodsUuid',
            					hidden:true,
            					formatter:function(value,options,rowData){
            						goodsUuid = value;
            					}
            				},
							{
								name:"decCm",
								label:"单耗",
								width : 80,
								hidden:true,
								formatter:function(value,options,rowData){
									console.log("[decCm]",decCm);
									decCm = value;
									return value;
                                },
							},
            				{
            					name : 'consumption',
            					label:"所需用量",
            					width : 80,
                                formatter:function(value,options,rowData){
                                	console.log('amount',amount);
                                	console.log('decCm',decCm);
                                	console.log('amount*decCm',amount*decCm);
                               	 	return amount*decCm;
                                },
    						},
    						{
    							name : 'inStockQty',
    							label:"当前库存",
    							width : 80,
							}
                ],
                cmTemplate: {
                    sortable: false,
                    title: false
                },
                page: 1,
                rowNum: 10,
                rowList: [10, 20, 30],
                pager: '#page_m',
                sortname: 'id',
                viewrecords: true,
                forceFit: false,
                rownumbers: true,
                multiselect: true,
                multiboxonly: true,
                sortorder: "desc",
                autoScroll: false,
                height: 150,
                altRows: true,
                gridview: true,
                autowidth: true,
                jsonReader: {
                    root: "data",
                    records: "data.totalRow",
                    total: "data.totalPage",
                },
            });
        },
        reLoadGrid: function () {
            $("#grid").jqGrid("setGridParam", {
            	url: grid_url+"/getList",
                datatype : "json",
                mtype : "POST",
                page:1,
                postData:{
                 
                }
            }).trigger("reloadGrid");
        },
        reLoadGrid_m: function () {
            $("#grid_m").jqGrid("setGridParam", {
                url: grid_url+"/getLoss",
                datatype : "json",
                mtype : "POST",
                page:1,
                postData:{
                    "orderNo" : orderNo
                }
            }).trigger("reloadGrid");
        },
        
        reLoadGrid_d: function () {
            $("#grid_d").jqGrid("setGridParam", {
                url: grid_url+"/getDetailList",
                datatype : "json",
                mtype : "POST",
                page:1,
                postData:{
                    "orderNo" : orderNo
                }
            }).trigger("reloadGrid");
        },
         reset: function () {
             model.query = {
                 
             };
             model.queryData();
         },
         queryData: function () {
             $("#grid").jqGrid("setGridParam", {
                 url: grid_url+"/getList",
                 datatype: "json",
                 mtype: 'POST',
                 page:1,
                 postData: model.query.$model
             }).trigger("reloadGrid");
         },
         /**审核订单*/
         examine:function(ids){
        	 console.log('this is [ids]````````',ids);
        	 dialog({
                 title: "确认操作",
                 content: "确定通过审核？ 此操作不可恢复！",
                 okValue: "确定",
	        	 ok: function () {
	        		 $.ajax({
	        		 type:"POST",
	        		 url:"/api/produce/doExamination",
	        		 data:{
	        			 "ids":ids
	        		 },
	        		 success: function () {
	        			 
	        			 model.reLoadGrid();
	        		 },
	        		 beforeSend: function (xhr) {
	                     xhr.setRequestHeader("X-AuthToken", token);
	                 },
	                 error: function (responseData, textStatus, errorThrown) {
	                     alert("Failed: " + responseData);
	                     model.reLoadGrid();
	                 }
	        	 });
	        	 },
	        	 cancelValue: "取消",
                 cancel: function () {
                	 model.reLoadGrid_d();
                 } 
        	 }).showModal();
         },
         /**
          * 完成订单生产
          */
         complete:function(ids){

        		 console.log('this is [ids]````````',ids);
            	 dialog({
                     title: "确认操作",
                     content: "确定完成此订单？",
                     okValue: "确定",
    	        	 ok: function () {
    	        		 $.ajax({
    	        		 type:"POST",
    	        		 url:"/api/produce/complete",
    	        		 data:{
    	        			 "id":ids
    	        		 },
    	        		 success: function () {
    	        			 
    	        			 model.reLoadGrid();
    	        		 },
    	        		 beforeSend: function (xhr) {
    	                     xhr.setRequestHeader("X-AuthToken", token);
    	                 },
    	                 error: function (responseData, textStatus, errorThrown) {
    	                     alert("Failed: " + responseData);
    	                 }
    	        	 });
    	        	 },
    	        	 cancelValue: "取消",
                     cancel: function () {} 
            	 }).showModal();
         },
         /**登记入库*/
         register:function(rowData,id,rowData_d){
        	 model.initproduction();
//        	 model.productiondetailInfo.id = id;
//        	 model.productiondetailInfo.already = already;
        	 console.log('[rowData.orderDetailUuid]',rowData_d);
        	 console.log('[rowData.orderDetailUuid]',rowData_d.orderDetailUuid);
        	 rowData.id = id;
	             dialog({
                 title: "确认操作",
                 content: $('#registers'),
                 okValue: "确定",
                 ok: function () {
                	 var already = model.productiondetailInfo.registerAmount;
                	 var register = model.productiondetailInfo.register;
                	 var registerDate = model.productiondetailInfo.registerDate;
                	 var goodsUuid = rowData.goodsUuid;
                	 var orderNo = rowData.orderNo;
                	 var orderDetailUuid = rowData_d.orderDetailUuid;
                	 console.log("rowData_d.amount",rowData_d.amount);
                	 console.log("rowData_d.already",rowData_d.already);
                	 console.log("model.productiondetailInfo.registerAmount",already);
                	 if(parseInt(rowData_d.amount) - (parseInt(already) + parseInt(rowData_d.already)) < 0){
                		 dialog({
                             title: "错误！",
                             content: "已生产数量已达总数上限，请勿登记入库！",
                             okValue: "确定",
            	        	 ok: function (){
            	        	 }
                    	 }).showModal();
                		 return;  
                	 }
                	 var register = {
                        	 already : parseInt(already),
                        	 register : register,
                        	 registerDate : registerDate,
                        	 goodsUuid : goodsUuid,
                        	 orderNo:orderNo,
                        	 orderDetailUuid:orderDetailUuid
                         }
                	 
                     $.ajax({
                    	 contentType: "application/json;charset=utf-8",
                         type: "POST",
                         url: "/api/produce/doRegister",
                         data:JSON.stringify(register),
                         beforeSend: function (xhr) {
                             xhr.setRequestHeader("X-AuthToken", token);
                         },
                         success: function (data, status, xhr) {
                        	 model.reLoadGrid();
                        	 model.reLoadGrid_d(orderNo);
                         },
                         error: function (responseData, textStatus, errorThrown) {
                             alert("Failed: " + responseData);
                             model.reLoadGrid_d(orderNo);
                         }
                     });
                 },
                 cancelValue: "取消",
                 cancel: function () {
                	 model.reLoadGrid_d(orderNo);
                 }
             }).showModal();
         },
         
         /**删除订单*/
         del: function (ids) {
             dialog({
                 title: "确认操作",
                 content: "确定删除？ 此操作不可恢复！",
                 okValue: "确定",
                 ok: function () {

                     $.ajax({
                         type: "POST",
                         url: "/api/produce/delete",
                         data: {
                             "ids": ids
                         },
                         beforeSend: function (xhr) {
                             xhr.setRequestHeader("X-AuthToken", token);
                         },
                         success: function (data, status, xhr) {
                             if (data) {
                                 $('#grid').jqGrid('delRowData', ids);
                             }
                             model.queryData();
                         },
                         error: function (responseData, textStatus, errorThrown) {
                             alert("Failed: " + responseData);
                         }

                     });
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
         addEvent: function () {
        	 
        	 $(".fr1").on("click", "#changeGridStatus0", function (e) {
        		 $("#grid_m").jqGrid("clearGridData");
        		 item = 0;
        		 $("#table1").show();
        		 $("#table2").hide();
        		 model.loadGrid_d();
        	 });
        	 $(".fr1").on("click", "#changeGridStatus1", function (e) {
        		 item = 1;
        		 $("#table2").show();
           		 $("#table1").hide();
        		 model.loadGrid_d();
        	 });
        	 
        	 var t = this;
        	//查看详情        	 
        	 $(".grid-wrap").on("click", "#detail", function (e) {
                 var t = $(this).parent().data("id");
                 var rowData = $("#grid").jqGrid('getRowData',t);
                 var orderNo = rowData.orderNo;
                 top.topManager.openPage({
         			id:"productionDetail",
         			title:"查看详情",
         			href:'index.html#!/114?orderNo='+orderNo,
         			reload:true
         		 })
             });
              //订单审核
        	 
             $("#examine").on("click",function (e) {
            	 var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                 var rowData = $("#grid").jqGrid('getRowData',t);
                 console.log('[rowDate.examination]',rowData);
                 if(rowData.examination == '已审核'){
                	 dialog({
                         title: "错误",
                         content: "请勿重复审核操作！",
                         okValue: "确定",
                         ok: function () {
                         },
                     }).showModal();
                 }else{
                	 e.preventDefault();
                     // if (Business.verifyRight("BU_DELETE")) {
                     var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                     t.length ? model.examine(t.join()) : parent.Public.tips({
                         type: 2,
                         content: "请选择要审核的订单！"
                     })
                 }
            	  
             });
             $("#complete").on("click",function (e) {
            	 var t = $(this).parent().data("id");
            	 var id = $("#grid").jqGrid("getGridParam", "selarrrow");
            	 var rowData = $("#grid").jqGrid('getRowData',id);
            	 console.log("111111111111111111111111111111111111111111111111",rowData.examination);
            	 if(rowData.examination === "未审核" || rowData.examination === ""){
            		 dialog({
                         title: "完成生产失败！请先审核订单！",
                         content: "完成生产失败！请先审核订单！",
                         okValue: "确定",
        	        	 ok: function (){
        	        	 }
                	 }).showModal();
            		 return;  
            	 }else{
            		 e.preventDefault();
                     // if (Business.verifyRight("BU_DELETE")) {
                     var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                     t.length ? model.complete(t.join()) : parent.Public.tips({
                         type: 2,
                         content: "请选择要审核的订单！"
                     }) 
            	 }
             });
             
             //登记入库
             $(".grid-wrap").on("click", ".register", function(){
            	 var t = $("#grid").jqGrid("getGridParam", "selarrrow");
            	 var rowData = $("#grid").jqGrid('getRowData',t);
            	 var a = $("#grid_d").jqGrid("getGridParam", "selarrrow");
            	 var rowData_d = $("#grid_d").jqGrid('getRowData',a);
            	 console.log("rowData",rowData);
            	 console.log("idididididididididid",t);
            	 
            	 if(t == ''){
            		 dialog({
                         title: "错误！",
                         content: "请选择要登记的订单！",
                         okValue: "确定",
        	        	 ok: function (){
        	        	 }
                	 }).showModal();
            		 return;  
            	 }
            	 if(rowData.examination != '已审核'){
            		 dialog({
                         title: "错误！",
                         content: "未审核的生产任务不能登记入库！请先审核订单！",
                         okValue: "确定",
        	        	 ok: function (){
        	        	 }
                	 }).showModal();
            		 return;  
            	 }
            	 if(rowData.status == '已完成'){
            		 dialog({
                         title: "错误！",
                         content: "该订单已完成，请勿登记！",
                         okValue: "确定",
        	        	 ok: function (){
        	        	 }
                	 }).showModal();
            		 return;  
            	 }
//            	 var already = rowData.already;
            	 
            	 model.register(rowData,t,rowData_d);
             });
             // 删除
             $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
                 var ei = [];
                 var e = $(this).parent().data("id");
                 ei.push(e);
                 model.del(e);
             });
             $("#search").click(function (e) {
                 e.preventDefault();
                 model.queryData();
             });
             $(".fa-refresh").click(function (e) {
                 e.preventDefault();
                 model.reset();
                 model.queryData();
             })
             $("#btn-batchDel").click(function (e) {
                 e.preventDefault();
                 // if (Business.verifyRight("BU_DELETE")) {
                 var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                 t.length ? model.del(t.join()) : parent.Public.tips({
                     type: 2,
                     content: "请选择需要删除的项"
                 })
             });
         },
         initproduction:function(){
	        	 model.productionInfo= {
             		id:"",
             		uuid:"",
             		productionNo:"",
             		startingDate:"",
             		destination:"",
             		freightForwarding:"",
             		ceva:"",
             		samDepartment:"",
             		qcDepartment:"",
             		productDepartment:"",
             		examination:"",
             		comment:"",
             		orderNo:"",
             		status:"",
             		issuedDate:""
	         }
           }
    })
    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {} // 切换菜单时销毁原来的view
    };
    return viewmod;
});
